package com.blades.monitor.core;

import com.blades.monitor.bean.MonitorItem;
import com.blades.monitor.constant.Constants;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.util.List;

import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

/**
 * Created by shuangjun.yang on 2016/3/18.
 * 获取业务监控
 */

public class FetchBusinessMonitor implements FetchMonitor {
    Logger logger = LoggerFactory.getLogger(FetchBusinessMonitor.class);

    @Override
    public List<MonitorItem> getMonitorItem(String url) {
        Document doc=null;
        try{
            doc = Jsoup.connect(url).timeout(Constants.URL_TIME_OUT).get();
        }catch(Exception e){
            e.printStackTrace();
            logger.error("Jsoup 链接监控目标地址{} 错误 {}",url,e.getMessage());
        }
        Element bodyElement = doc.body();
        return getMonitorItemDetail(bodyElement.ownText());
    }


    private List<MonitorItem> getMonitorItemDetail(String bodyText){
        List<String> monitorStrList = Lists.newArrayList();
        if(StringUtils.isNotBlank(bodyText)){
             monitorStrList =  Splitter.on(" ").omitEmptyStrings().splitToList(bodyText);
        }
        return getMonitorItem(monitorStrList);
    }

    private List<MonitorItem> getMonitorItem(List<String> monitorStrList){
        List<MonitorItem> monitorItems = Lists.newArrayList();
        if(!CollectionUtils.isEmpty(monitorStrList)){
            for(String monitorStr : monitorStrList){
                List<String> monitorItemStr = Splitter.on("=").omitEmptyStrings().splitToList(monitorStr);
                if(!CollectionUtils.isEmpty(monitorItemStr) && monitorItemStr.size() == 2){
                    MonitorItem monitorItem = new MonitorItem(monitorItemStr.get(0),Double.valueOf(monitorItemStr.get(1)));
                    monitorItems.add(monitorItem);
                }
            }
        }
        return monitorItems;
    }
}
